//
//  UINavigationBar+Alpha.m
//  ITC_iOS
//
//  Created by iBenz on 2018/10/9.
//  Copyright © 2018年 Benz.L. All rights reserved.
//

#import "UINavigationBar+Alpha.h"
#import <objc/runtime.h>

static NSString *const kBackgroundImageKey = @"kBackgroundImageKey";

@implementation UINavigationBar(Alpha)
@dynamic opacity;

- (void)setOpacity:(CGFloat)opacity {
    NSLog(@"%@", @(opacity));
    [self setBackgroundImage:[self alpha:opacity image:self.backgroundImage] forBarMetrics:UIBarMetricsDefault];
    self.shadowImage = [UIImage new];
    self.translucent = opacity<1.0?YES:NO;
    self.backgroundColor = UIColor.clearColor;
}

- (void)setBackgroundImage:(UIImage *)backgroundImage {
    objc_setAssociatedObject(self, &kBackgroundImageKey, backgroundImage, OBJC_ASSOCIATION_COPY);
}

- (UIImage *)backgroundImage {
    UIImage *image = objc_getAssociatedObject(self, &kBackgroundImageKey);
    if (!image) {
        image = [self imageFromView:self.subviews.firstObject];
        self.backgroundImage = image;
    }
    return image;
}

//设置图片透明度
- (UIImage *)alpha:(CGFloat)alpha image:(UIImage*)image {
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0.0f);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect area = CGRectMake(0, 0, image.size.width, image.size.height);
    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -area.size.height);
    CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
    CGContextSetAlpha(ctx, alpha);
    CGContextDrawImage(ctx, area, image.CGImage);
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (UIImage *)imageFromView:(UIView *)view {
    CGSize size = view.bounds.size;
    //下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

@end
